package com.zhuozhengsoft.pageoffice6springboot2back.controller;

import com.zhuozhengsoft.pageoffice.OpenModeType;
import com.zhuozhengsoft.pageoffice.PageOfficeCtrl;
import com.zhuozhengsoft.pageoffice.word.DataRegionReader;
import com.zhuozhengsoft.pageoffice.word.DataRegionWriter;
import com.zhuozhengsoft.pageoffice.word.WordDocumentReader;
import com.zhuozhengsoft.pageoffice.word.WordDocumentWriter;
import com.zhuozhengsoft.pageoffice6springboot2back.util.GetDirPathUtil;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.FileOutputStream;
import java.io.IOException;


@RestController
@RequestMapping(value = "/SplitWord")
public class SplitWordController {

    //获取doc目录的磁盘路径
    private final String dir = GetDirPathUtil.getDirPath() + "static/doc/";

    public SplitWordController() throws IOException {
    }

    @RequestMapping(value = "/Word")
    public String showWord(HttpServletRequest request) {
        PageOfficeCtrl poCtrl = new PageOfficeCtrl(request);

        WordDocumentWriter wordDoc = new WordDocumentWriter();
        //打开数据区域，openDataRegion方法的参数代表Word文档中的书签名称
        DataRegionWriter dataRegion1 = wordDoc.openDataRegion("PO_test1");
        dataRegion1.setSubmitAsFile(true);
        DataRegionWriter dataRegion2 = wordDoc.openDataRegion("PO_test2");
        dataRegion2.setSubmitAsFile(true);
        dataRegion2.setEditing(true);
        DataRegionWriter dataRegion3 = wordDoc.openDataRegion("PO_test3");
        dataRegion3.setSubmitAsFile(true);
        poCtrl.setWriter(wordDoc);
        //打开文档
        poCtrl.webOpen("/doc/SplitWord/test.docx", OpenModeType.docNormalEdit, "张三");
        return poCtrl.getHtml();
    }


    @RequestMapping("save")
    public void save(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String filePath = dir + "SplitWord/";
        WordDocumentReader doc = new WordDocumentReader(request, response);
        byte[] bWord;

        DataRegionReader dr1 = doc.openDataRegion("PO_test1");
        bWord = dr1.getFileBytes();
        FileOutputStream fos1 = new FileOutputStream(filePath + "new1.docx");
        fos1.write(bWord);
        fos1.flush();
        fos1.close();

        DataRegionReader dr2 = doc.openDataRegion("PO_test2");
        bWord = dr2.getFileBytes();
        FileOutputStream fos2 = new FileOutputStream(filePath + "new2.docx");
        fos2.write(bWord);
        fos2.flush();
        fos2.close();

        DataRegionReader dr3 = doc.openDataRegion("PO_test3");
        bWord = dr3.getFileBytes();
        FileOutputStream fos3 = new FileOutputStream(filePath + "new3.docx");
        fos3.write(bWord);
        fos3.flush();
        fos3.close();

        doc.close();
    }

}
